﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Xml.Linq;
using Wolfpack.Core;

namespace Wolfpack.Contrib.Deployment.NUnit
{
    public class NUnitXmlResultFileParser : INUnitResultFileParser
    {
        public NUnitResult Parse(string resultFile)
        {
            var result = new NUnitResult();
            var xml = XElement.Load(SmartLocation.GetLocation(resultFile));
            var attributes = xml.Attributes();

            typeof (NUnitResult).GetProperties().ToList()
                .ForEach(pi =>
                             {
                                 XAttribute attr;

                                 // exceptions to attribute name => property name
                                 if (pi.Name == "NotRun")
                                 {
                                     attr = attributes.First(a => a.Name.LocalName == "not-run");
                                 }
                                 else
                                 {
                                     attr = attributes.FirstOrDefault(a => string.Compare(a.Name.LocalName, pi.Name,
                                         StringComparison.OrdinalIgnoreCase) == 0);
                                 }

                                 if (attr == null)
                                     return;

                                 var converter = new Int32Converter();
                                 var value = converter.ConvertFrom(attr.Value);

                                 pi.SetValue(result, value, null);
                             });

            return result;
        }
    }
}